package com.vegetable.modules.controller.finance;

import com.alibaba.fastjson.JSONObject;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.finance.TransactionPaymentMatch;
import com.vegetable.modules.entity.finance.po.TransactionPaymentMatchPO;
import com.vegetable.modules.entity.finance.vo.TransactionPaymentMatchVO;
import com.vegetable.modules.exception.TransactionPaymentMatchException;
import com.vegetable.modules.service.finance.ITransactionPaymentMatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 交易流水与付款记录匹配关系 前端控制器
 * </p>
 *
 * @author Qoder
 * @since 2025-11-02
 */
@Slf4j
@RestController
@RequestMapping("/finance/transaction-payment-match")
@Api(tags = "交易流水与付款记录匹配关系")
public class TransactionPaymentMatchController extends AbstractController {

    @Autowired
    private ITransactionPaymentMatchService transactionPaymentMatchService;

    /**
     * 根据付款记录ID查询关联的所有交易流水
     */
    @GetMapping("/list-by-payment/{paymentId}")
    @ApiOperation("根据付款记录ID查询关联的所有交易流水")
    public R<List<TransactionPaymentMatchVO>> listByPaymentId(
            @ApiParam(value = "付款记录ID", required = true) @PathVariable("paymentId") Long paymentId) {
        List<TransactionPaymentMatchVO> list = transactionPaymentMatchService.listByPaymentId(paymentId);
        return R.data(list);
    }
    
    /**
     * 根据付款记录ID查询关联的所有交易流水利息（包含交易流水信息）
     */
    @GetMapping("/list-by-payment-with-transaction/{paymentId}")
    @ApiOperation("根据付款记录ID查询关联的所有交易流水利息（包含交易流水信息）")
    public R<List<TransactionPaymentMatch>> listByPaymentIdWithTransactionInfo(
            @ApiParam(value = "付款记录ID", required = true) @PathVariable("paymentId") Long paymentId) {
        List<TransactionPaymentMatch> list = transactionPaymentMatchService.listByPaymentIdWithTransactionInfo(paymentId);
        return R.data(list);
    }

    /**
     * 根据交易流水ID查询关联的付款记录
     */
    @GetMapping("/list-by-transaction/{transactionId}")
    @ApiOperation("根据交易流水ID查询关联的付款记录")
    public R<List<TransactionPaymentMatch>> listByTransactionId(
            @ApiParam(value = "交易流水ID", required = true) @PathVariable("transactionId") Long transactionId) {
        List<TransactionPaymentMatch> list = transactionPaymentMatchService.listByTransactionId(transactionId);
        return R.data(list);
    }
    
    /**
     * 根据交易流水ID查询关联的付款记录（包含付款记录信息）
     */
    @GetMapping("/list-by-transaction-with-payment/{transactionId}")
    @ApiOperation("根据交易流水ID查询关联的付款记录（包含付款记录信息）")
    public R<List<TransactionPaymentMatch>> listByTransactionIdWithPaymentInfo(
            @ApiParam(value = "交易流水ID", required = true) @PathVariable("transactionId") Long transactionId) {
        List<TransactionPaymentMatch> list = transactionPaymentMatchService.listByTransactionIdWithPaymentInfo(transactionId);
        return R.data(list);
    }

    /**
     * 根据付款记录ID查询关联的所有交易流水（包含详细信息）
     */
    @GetMapping("/vo/list-by-payment/{paymentId}")
    @ApiOperation("根据付款记录ID查询关联的所有交易流水（包含详细信息）")
    public R<List<TransactionPaymentMatchVO>> listVOByPaymentId(
            @ApiParam(value = "付款记录ID", required = true) @PathVariable("paymentId") Long paymentId) {
        List<TransactionPaymentMatchVO> list = transactionPaymentMatchService.listVOByPaymentId(paymentId);
        return R.data(list);
    }

    /**
     * 根据交易流水ID查询关联的付款记录（包含详细信息）
     */
    @GetMapping("/vo/list-by-transaction/{transactionId}")
    @ApiOperation("根据交易流水ID查询关联的付款记录（包含详细信息）")
    public R<List<TransactionPaymentMatchVO>> listVOByTransactionId(
            @ApiParam(value = "交易流水ID", required = true) @PathVariable("transactionId") Long transactionId) {
        List<TransactionPaymentMatchVO> list = transactionPaymentMatchService.listVOByTransactionId(transactionId);
        return R.data(list);
    }

    /**
     * 根据付款记录ID查询已匹配的总金额
     */
    @GetMapping("/matched-amount/{paymentId}")
    @ApiOperation("根据付款记录ID查询已匹配的总金额")
    public R<BigDecimal> getMatchedAmountByPaymentId(
            @ApiParam(value = "付款记录ID", required = true) @PathVariable("paymentId") Long paymentId) {
        BigDecimal amount = transactionPaymentMatchService.getMatchedAmountByPaymentId(paymentId);
        return R.data(amount);
    }

    /**
     * 删除指定付款记录与交易流水的关联关系
     */
    @PostMapping("/remove")
    @ApiOperation("删除指定付款记录与交易流水的关联关系")
    public R<Boolean> removeByPaymentIdAndTransactionId(@RequestBody TransactionPaymentMatchPO matchPO) {
        log.info("删除指定付款记录与交易流水的关联关系: {}", JSONObject.toJSONString(matchPO));
        boolean result = transactionPaymentMatchService.removeByPaymentIdAndTransactionId(
                matchPO.getPaymentId(), matchPO.getTransactionId());
        return R.success(result ? "删除成功" : "删除失败");
    }

    /**
     * 重新分配交易流水到目标付款记录（支持新增分配和调整分配）
     */
    @PostMapping("/reallocate")
    @ApiOperation("重新分配交易流水到目标付款记录（支持新增分配和调整分配）")
    public R<Boolean> reallocateTransactionToPayment(
            @ApiParam(value = "参数对象", required = true) @RequestBody TransactionPaymentMatchPO matchPO) {
        try {
            boolean result = transactionPaymentMatchService.reallocateTransactionToPayment(
                    matchPO.getTransactionId(), matchPO.getPaymentId(), matchPO.getAllocateAmount());
            return R.success(result ? "重新分配成功" : "重新分配失败");
        } catch (TransactionPaymentMatchException e) {
            log.error("重新分配交易流水到目标付款记录时发生业务异常: ", e);
            return R.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("重新分配交易流水到目标付款记录时发生系统异常: ", e);
            return R.fail("系统异常，请联系管理员");
        }
    }
}